package com.nulstudio.sppm.Controller;

import com.alibaba.fastjson2.JSONObject;
import com.nulstudio.sppm.Entities.UserInfo;
import com.nulstudio.sppm.Service.UserInfoService;
import com.nulstudio.sppm.Utils.EncodingUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@Controller
@RestController
@RequestMapping("/register")
public class RegisterController {
    @Autowired
    private UserInfoService userInfoService;
    @PostMapping(value="/registerpage",produces="application/json;charset=UTF-8")
    public String register(@RequestBody Map<String,String> map){
        JSONObject json = new JSONObject();
        String[] properties = new String[]{"uName","rName","gender","authority","headportrait","password"};
        UserInfo userInfo = new UserInfo();
        for (String property : properties) {
            if (!map.containsKey(property)) {
                json.put("code", 300);
                json.put("message", property + " missed");
                json.put("version", 1);
                return json.toJSONString();
            }
        }
        if(map.containsKey(properties[0]) && userInfoService.checkRepeatedUName(map.get("uName"))){
            json.put("code",301);
            json.put("message","repeated uName");
            json.put("version",1);
            return json.toJSONString();
        }
        userInfo.setrName(map.get("rName"));
        userInfo.setuName(map.get("uName"));
        userInfo.setGender(map.get("gender"));
        userInfo.setAuthority(map.get("authority"));
        userInfo.setPassword(map.get("password"));
        userInfo.setHeadportrait(map.get("headportrait"));
        json.put("code",100);
        json.put("message", "success");
        json.put("version",1);
        userInfoService.addUserInfo(userInfo);
        return json.toJSONString();
    }
}
